package com.sqtracker.recommender.service;

import com.sqtracker.recommender.model.TorrentScore;
import com.sqtracker.recommender.repository.TorrentScoreRepository;
import com.sqtracker.recommender.repository.RatingRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class TorrentScoreService {
    private static final Logger logger = LoggerFactory.getLogger(TorrentScoreService.class);

    private final TorrentScoreRepository torrentScoreRepository;
    private final RatingRepository ratingRepository;

    // 贝叶斯平均参数
    private static final double BAYESIAN_C = 10.0; // 先验评分数量
    private static final double BAYESIAN_M = 3.0;  // 先验评分均值

    @Autowired
    public TorrentScoreService(TorrentScoreRepository torrentScoreRepository,
                             RatingRepository ratingRepository) {
        this.torrentScoreRepository = torrentScoreRepository;
        this.ratingRepository = ratingRepository;
    }

    /**
     * 计算技术维度得分
     */
    private double calculateTechnicalScore(double downloadSuccessRate, int seedersCount) {
        // 下载成功率得分 (权重60%)
        double successRateScore;
        if (downloadSuccessRate >= 0.9) {
            successRateScore = 100.0;
        } else if (downloadSuccessRate <= 0.3) {
            successRateScore = 0.0;
        } else {
            successRateScore = (downloadSuccessRate - 0.3) / 0.6 * 100;
        }

        // 做种节点得分 (权重40%)
        double seedersScore;
        if (seedersCount >= 50) {
            seedersScore = 100.0;
        } else if (seedersCount <= 10) {
            seedersScore = Math.max(0, seedersCount * 10.0);
        } else {
            seedersScore = 50.0 + (seedersCount - 10) * 1.25;
        }

        return (successRateScore * 0.6 + seedersScore * 0.4) * 0.3; // 技术维度总权重30%
    }

    /**
     * 计算内容维度得分
     */
    private double calculateContentScore(double userRatingAverage, int userRatingCount) {
        // 使用贝叶斯平均
        double bayesianAverage = ((BAYESIAN_C * BAYESIAN_M) + (userRatingAverage * userRatingCount)) 
                                / (BAYESIAN_C + userRatingCount);
        
        // 转换为百分制
        return (bayesianAverage / 5.0) * 100 * 0.5; // 内容维度总权重50%
    }

    /**
     * 计算社区维度得分
     */
    private double calculateCommunityScore(double averageResponseTime, double longTermValue) {
        // 响应时间得分 (权重60%)
        double responseTimeScore;
        if (averageResponseTime <= 12) {
            responseTimeScore = 100.0;
        } else if (averageResponseTime >= 48) {
            responseTimeScore = 0.0;
        } else {
            responseTimeScore = 100.0 - ((averageResponseTime - 12) / 36 * 100);
        }

        // 长期价值得分 (权重40%)，假设longTermValue已经是0-1的标准化值
        double longTermScore = longTermValue * 100;

        return (responseTimeScore * 0.6 + longTermScore * 0.4) * 0.2; // 社区维度总权重20%
    }

    /**
     * 计算最终得分
     */
    public void calculateAndUpdateScore(String torrentId) {
        Optional<TorrentScore> scoreOpt = torrentScoreRepository.findByTorrentId(torrentId);
        TorrentScore score = scoreOpt.orElse(new TorrentScore());
        
        if (!scoreOpt.isPresent()) {
            score.setTorrentId(torrentId);
            score.setCreatedAt(new Date());
        }

        // 这里需要从其他服务获取实际数据
        // TODO: 集成实际数据源
        double downloadSuccessRate = 0.85; // 示例值
        int seedersCount = 30;            // 示例值
        double averageResponseTime = 24.0; // 示例值
        double longTermValue = 0.75;       // 示例值

        // 获取用户评分数据
        double userRatingAverage = ratingRepository.getAverageScoreByTorrentId(torrentId);
        long ratingCount = ratingRepository.countByTorrentId(torrentId);

        // 计算各维度得分
        double technicalScore = calculateTechnicalScore(downloadSuccessRate, seedersCount);
        double contentScore = calculateContentScore(userRatingAverage, (int)ratingCount);
        double communityScore = calculateCommunityScore(averageResponseTime, longTermValue);

        // 更新评分对象
        score.setDownloadSuccessRate(downloadSuccessRate);
        score.setSeedersCount(seedersCount);
        score.setTechnicalScore(technicalScore);
        score.setUserRatingAverage(userRatingAverage);
        score.setUserRatingCount((int)ratingCount);
        score.setContentScore(contentScore);
        score.setAverageResponseTime(averageResponseTime);
        score.setLongTermValue(longTermValue);
        score.setCommunityScore(communityScore);
        score.setFinalScore(technicalScore + contentScore + communityScore);
        score.setLastUpdated(new Date());

        // 保存更新
        torrentScoreRepository.save(score);
    }

    /**
     * 定时更新所有种子评分
     * 每6小时执行一次
     */
    @Scheduled(fixedRate = 6 * 60 * 60 * 1000)
    public void updateAllScores() {
        logger.info("Starting scheduled update of all torrent scores");
        // TODO: 获取所有需要更新的种子ID
        List<TorrentScore> scores = torrentScoreRepository.findAll();
        for (TorrentScore score : scores) {
            try {
                calculateAndUpdateScore(score.getTorrentId());
            } catch (Exception e) {
                logger.error("Error updating score for torrent {}: {}", 
                    score.getTorrentId(), e.getMessage());
            }
        }
        logger.info("Completed scheduled update of all torrent scores");
    }

    /**
     * 获取种子评分
     */
    public Optional<TorrentScore> getScore(String torrentId) {
        return torrentScoreRepository.findByTorrentId(torrentId);
    }

    /**
     * 获取评分最高的种子
     */
    public List<TorrentScore> getTopScores() {
        return torrentScoreRepository.findTop10ByOrderByFinalScoreDesc();
    }
} 